package org.com.android.network;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Map;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.params.ConnManagerParams;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.util.EntityUtils;


import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.util.Log;


public class NetworkClient {
	private HttpClient client;
	private String url;
	private boolean login ;
	private String username ;
	private String password ;
	
	public final static int REGISTRATION_TIMEOUT = 30 * 1000;
	
	public HttpClient getclient() {
		if (client == null) {
			client = new DefaultHttpClient();
			final HttpParams params = client.getParams();
			HttpConnectionParams.setConnectionTimeout(params,
					REGISTRATION_TIMEOUT);
			HttpConnectionParams.setSoTimeout(params, REGISTRATION_TIMEOUT);
			ConnManagerParams.setTimeout(params, REGISTRATION_TIMEOUT);
		}
		return client;
	}

	public NetworkClient(String url,String username,String password) {
		seturl(url);
		getclient();
		this.username = username ;
		this.password = password ;
	}
	
	public void seturl(String url){
		if (this.url != url){
			this.url = url ;
			this.login = false ;
		}
	}

	public boolean authenticate(String target, Handler handler) {
		final HttpResponse resp;

		final ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair("username", this.username));
		params.add(new BasicNameValuePair("password", this.password));
		
		HttpEntity entity = null;
		try {
			entity = new UrlEncodedFormEntity(params);
		} catch (final UnsupportedEncodingException e) {
			throw new AssertionError(e);
		}
		
		String login_url = this.url + target ;
		final HttpPost post = new HttpPost(login_url);
		post.addHeader(entity.getContentType());
		post.setEntity(entity);
		
		Message msg = handler.obtainMessage();
		
		try {
			resp = getclient().execute(post);
			if (resp.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
				if (Log.isLoggable("TAG", Log.VERBOSE)) {
					Log.v("TAG", "Successful authentication");
				}
				return true;
			} else {
				if (Log.isLoggable("TAG", Log.VERBOSE)) {
					Log.v("TAG", "Error authenticating" + resp.getStatusLine());
				}
				return false;
			}
		} catch (final IOException e) {
			if (Log.isLoggable("TAG", Log.VERBOSE)) {
				Log.v("TAG", "IOException when getting authtoken", e);
			}
			return false;
		} finally {
			if (Log.isLoggable("TAG", Log.VERBOSE)) {
				Log.v("TAG", "getAuthtoken completing");
			}
		}
	}

	public String post(String target, Map<String, String> parammap) {
		//if (this.login == false){
		//	Log.d("NetworkClient::authenticate","login first");
		//	return null ;
		//}
		
		ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();
		for (Map.Entry<String, String> entry : parammap.entrySet()) {
			String key = entry.getKey();
			String value = entry.getValue();
			params.add(new BasicNameValuePair(key,value));
		}
		
		String result = null ;
		try {
			HttpEntity entity = new UrlEncodedFormEntity(params);
			String target_url = this.url ;
			if (target != null && target.length() > 0){
				target_url += target ;
			}
			final HttpPost request = new HttpPost(target_url);
			
			request.addHeader(entity.getContentType());
			request.setEntity(entity);
			HttpResponse response = getclient().execute(request);
			if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
				if (Log.isLoggable("TAG", Log.VERBOSE)) {
					Log.v("TAG", "Successful authentication");
				}
				result = EntityUtils.toString(response.getEntity());
				Log.v("NetworkClient::post",result);
			} else {
				if (Log.isLoggable("TAG", Log.VERBOSE)) {
					Log.v("TAG", "Error authenticating" + response.getStatusLine());
				}
			}
		} catch (UnsupportedEncodingException e) {
			Log.e("NetworkClient::post", e.getMessage());
		} catch (IOException e) {
			Log.e("NetworkClient::post", e.getMessage());
		} catch (Exception e) {
			Log.e("NetworkClient::post", e.toString());
		}
		return result ;
	}
}